<template>
  <div class="container">
    <div>
      <label>Prompt</label>
      <button @click='gererator'>生成</button>
      <textarea class="input" v-model="prompt"></textarea>
    </div>
    <div class="output">
      <img :src="imgUrl" alt="">
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
const prompt = ref('一只可爱的小花猫')
const imgUrl = ref('')


const gererator = async () => {
  const negativeWords = 'Blurry, Bad, Bad anatomy, Bad proportions, Deformed, Disconnected limbs, Disfigured, Extra arms, Extra limbs, Extra hands, Fused fingers, Gross proportions, Long neck, Malformed limbs, Mutated, Mutated hands, Mutated limbs, Missing arms, Missing fingers, Poorly drawn hands, Poorly drawn face.';
  const endpoint =  `/klingai/v1/images/generations`
  const token = await (await fetch('/api/jwt-auth')).text()
  
  const headers = {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`,
  }
  const payload = {
    prompt: prompt.value,
    negative_prompt: negativeWords,
    aspect_ratio: '1:1'
  }
  const res = await fetch(endpoint, {
    method: 'POST',
    headers,
    body: JSON.stringify(payload),
  })
  if (res.status >= 400) {
    throw new Error("请求失败");
  }

  const ret = await res.json()
 
  const id = ret.data.task_id
  const resultUrl = `/klingai/v1/images/generations/${id}`
  imgUrl.value = 'https://res.bearbobo.com/resource/upload/a3IZyOsZ/loading-giaz5ycpd7j.gif'
  
  // 轮询结果
  do {
    await new Promise((resolve) => setTimeout(resolve, 300))
    const result = await fetch(resultUrl, {
      headers
    })
    const resultData = await result.json()
    const taskStatus = resultData.data.task_status
    if (taskStatus === 'processing' || taskStatus === 'submitted') {
      continue
    }
    if (taskStatus === 'failed') {
      throw new Error("图片生成失败");
    }

    const sample = resultData.data.task_result
    console.log(sample);
    
    if (sample) {
      imgUrl.value = sample.images[0].url
    }  else {
      imgUrl.value = 'https://res.bearbobo.com/resource/upload/vNg4ALJv/6659895-ox36cbkajrr.png'
    }

    break;

  } while (true)

}

</script>

<style lang="css" scoped>
  .input {
    width: 100%;
    height: 2rem;
    font-size: 1rem;
    padding: 0.5rem;
    border: 1px solid #ccc;
    border-radius: 0.5rem;
  }

  .progress {
    width: 100%;
    height: 0.1rem;
    margin: .4rem 0;
    background: #ccc;
  }

  .progress>div {
    background: #c00;
    height: 100%;
  }

  .container {
    display: flex;
    flex-direction: column;
    align-items: start;
    justify-content: start;
    height: 100vh;
  }

  .output {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 200px;
    border: 1px solid #ccc;
  }

  .output>img {
    width: 100%;
    max-width: 600px;
  }
</style>
